package com.aqie.hard.design;

import com.aqie.easy.structure.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 297 31ms
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        List<String> list = new ArrayList<>();
        getList(list,root);
        StringBuilder b = new StringBuilder("[");
        for(int i = 0; i < list.size(); i++){
            b.append(list.get(i));
            if(i!= list.size()-1){
                b.append(",");
            }
        }
        b.append("]");
        return b.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        data = data.substring(1,data.length()-1);
        String strs[] = data.split(",");
        TreeNode node = getNode(strs, new int[]{0});
        return node;
    }

    private void getList(List<String> list,TreeNode root){
        if(root == null){
            list.add(null);
            return;
        }
        list.add(String.valueOf(root.val));
        getList(list,root.left);
        getList(list,root.right);
    }

    private TreeNode getNode(String[] strs,int[] index){
        if(index[0] >= strs.length || strs[index[0]].isEmpty() || strs[index[0]].equals("null")){
            index[0]++;
            return null;
        }
        TreeNode node = new TreeNode(Integer.valueOf(strs[index[0]]));
        index[0]++;
        node.left = getNode(strs, index);
        node.right = getNode(strs, index);
        return node;
    }
}
